import Mock from "mockjs";

const Random = Mock.Random;

/**
 * 将字符串url转换为正则匹配
 * 转正则的原因：如果url是字符串类型，默认会完全匹配mock地址与应用请求地址，参数不同也会造成mock拦截失效，解决方式就是用正则匹配
 * @param {String} url 接口地址
 * @return {RegExp} 返回正则匹配规则
 */
function regUrl(url) {
  let urlStr = process.env.VUE_APP_BASE_URL + url + ".*";
  return RegExp(urlStr);
}

// 登录
Mock.mock(RegExp("/sys/login" + ".*"), /get|post/i, options => {
  console.log(options);
  return true;
  // let { username, password } = JSON.parse(option.body);
  // return username === "admin" && password === "admin";
});

// 用户数据
const userData = () => {
  let users = [];
  for (let i = 0; i < 10; i++) {
    let user = {
      id: i + 1,
      date: Random.date("yyyy-MM-dd"),
      name: Random.cname(),
      address: Mock.mock("@county(true)"),
      phone: Mock.mock(/^1[0-9]{10}$/),
      status: Random.integer(0, 1)
    };
    users.push(user);
  }
  return users;
};
Mock.mock(regUrl("/getUserInfo"), "post", options => {
  console.log(JSON.parse(options.body).username);
  return userData();
});
